package com.cby.android.olive.ext

import android.text.TextUtils
import android.util.Log

/**
 * @description: LogExt
 * @author: ChenBaoYang
 * @createDate: 2022/6/23 6:50 下午
 */
var customTagPrefix: String = "Chenby34"

fun String.logI(){
    val element:StackTraceElement? = getCallerStackTraceElement()
    if(element == null) {
        Log.i(customTagPrefix,this)
    }else{
        val tag = generateTag(element)
        Log.i(tag, this)
    }
}

fun String.logD(){
    val element:StackTraceElement? = getCallerStackTraceElement()
    if(element == null) {
        Log.d(customTagPrefix,this)
    }else{
        val tag = generateTag(element)
        Log.d(tag, this)
    }
}

fun String.logE(){
    val element:StackTraceElement? = getCallerStackTraceElement()
    if(element == null) {
        Log.e(customTagPrefix,this)
    }else{
        val tag = generateTag(element)
        Log.e(tag, this)
    }
}

fun String.logW(){
    val element:StackTraceElement? = getCallerStackTraceElement()
    if(element == null) {
        Log.w(customTagPrefix,this)
    }else{
        val tag = generateTag(element)
        Log.w(tag, this)
    }
}

fun getCallerStackTraceElement(): StackTraceElement? {
    return Thread.currentThread().stackTrace[4]
}


private fun generateTag(caller: StackTraceElement): String? {
    var tag = "%s.%s(L:%d)"
    var callerClazzName = caller.className
    callerClazzName = callerClazzName.substring(callerClazzName.lastIndexOf(".") + 1)
    tag = String.format(tag, callerClazzName, caller.methodName, caller.lineNumber)
    tag = if (TextUtils.isEmpty(customTagPrefix)) tag else "$customTagPrefix:$tag"
    return tag
}